package love.contact.data;

import java.io.File;
import android.content.Context;
import wwk.common.json.JSONObject;
import wwk.common.util.FileUtil;
import wwk.common.util.JsonUtil;

public class Setting 
{
	public int monitorServiceEnabled=1;
	
	public double requestTimestamp;//Millis
	public int serverVersionCode;
	public String serverVersionName; 
	
	final private String SettingFileName="setting";
	
	public void load(Context context)
	{
		File file=context.getFileStreamPath(SettingFileName);
		if(file.exists())
		{
			byte[] bytes=FileUtil.read(file);
			if(bytes!=null)
			{
				JSONObject json=JsonUtil.createJsonObject(bytes);

				monitorServiceEnabled=JsonUtil.getInt(json, "monitorServiceEnabled",1);
				serverVersionCode=JsonUtil.getInt(json, "serverVersionCode", -1);
				serverVersionName=JsonUtil.getString(json, "serverVersionName");
				requestTimestamp=JsonUtil.getDouble(json, "requestTimestamp", -1);
			}
		}
	}
	
	public boolean isMonitorServiceEnabled()
	{
		return 1==monitorServiceEnabled;
	}
	
	public boolean isRequireRquestConfig(int packageVCode)
	{
		boolean require=false;

		if(serverVersionCode<=packageVCode)
		{
			long currentTimeMillis=System.currentTimeMillis();
			
			final long MaxInterval=1000*60*60*24*7;
			if(requestTimestamp<=0 || currentTimeMillis-requestTimestamp>=MaxInterval)
			{
				require=true;
			}
		}
		
		return require;
	}
	
	public void save(Context context)
	{
		JSONObject json=new JSONObject();
		
		JsonUtil.putToJsonObject(json, "monitorServiceEnabled", monitorServiceEnabled);
		JsonUtil.putToJsonObject(json, "requestTimestamp", requestTimestamp);
		JsonUtil.putToJsonObject(json, "serverVersionCode", serverVersionCode);
		JsonUtil.putToJsonObject(json, "serverVersionName", serverVersionName);
		
		File file=context.getFileStreamPath(SettingFileName);
		String str=json.toString();
		byte[] bytes=str.getBytes();
		FileUtil.write(file, bytes, -1, false);
	}
}
